package models

import (
	"context"
	"fmt"
	"github.com/go-redis/redis/v8"
	"gorm.io/driver/mysql"
	"gorm.io/gorm"
	"time"
)

var DB *gorm.DB
var err error
var Rdb *redis.Client
var Ctx = context.Background()

func Init() {
	Dsn := "root:89B158B4DAFE6F5461878D26EA49B100@tcp(14.103.158.217:3306)/book_manage?charset=utf8&parseTime=True&loc=Local"
	DB, err = gorm.Open(mysql.Open(Dsn))
	if err != nil {
		fmt.Println("MYSQL连接失败")
		return
	}
	err = DB.AutoMigrate(&Order{}, &Student{}, &Book{})
	if err != nil {
		fmt.Println("MYSQL数据表迁移失败")
		return
	}
	fmt.Println("mysql预处理完成")

	Rdb = redis.NewClient(&redis.Options{
		Addr:     "14.103.158.217:6379",
		Password: "redis_x3jTtC", // no password set
		DB:       0,              // use default DB
	})

	err = Rdb.Set(Ctx, "key", "value", 0).Err()
	if err != nil {
		panic(err)
	}

	fmt.Println("redis链接成功")
}

func MysqlIntoRedis() {
	var Books []Book
	var Students []Student
	var Orders []Order
	err := DB.Debug().Find(&Books).Error
	if err != nil {
		panic(err)
	}
	err = DB.Debug().Find(&Students).Error
	if err != nil {
		panic(err)
	}
	err = DB.Debug().Find(&Orders).Error
	if err != nil {
		panic(err)
	}
	for _, book := range Books {
		err := Rdb.Set(Ctx, fmt.Sprintf("book:%d", book.ID), book.Name, 24*time.Hour).Err()
		if err != nil {
			panic(err)
		}
	}
	for _, student := range Students {
		err := Rdb.Set(Ctx, fmt.Sprintf("student:%d", student.ID), student.Name, 24*time.Hour).Err()
		if err != nil {
			panic(err)
		}
	}
	for _, order := range Orders {
		err := Rdb.HSet(Ctx, fmt.Sprintf("order:%d", order.ID), "student_id", order.UserId, "book_id", order.BookId, "Condition", order.Condition, "CreatedAt", order.CreatedAt).Err()
		if err != nil {
			panic(err)
		}
	}
}
